package com.ray.friendslist.wall;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.ray.friendslist.content.common.JSONModel;

public class WallEntity extends JSONModel {
	private JSONObject mJsonObjectItem;

	public WallEntity(JSONObject jsonObject) throws JSONException {
		mJsonObjectItem = jsonObject;
		Log.w("ray", "JSON IS"+mJsonObjectItem.toString(1));
	}

	public String getFeedText() throws JSONException {
		return android.text.Html.fromHtml(mJsonObjectItem.getString("text"))
				.toString();
	}

	public String getItemDate() throws NumberFormatException, JSONException {
		long seconds = Long.valueOf(mJsonObjectItem.getString("date"));
		SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm",
				Locale.getDefault());
		GregorianCalendar calendar = new GregorianCalendar(
				TimeZone.getDefault());
		calendar.setTimeInMillis(seconds * 1000);
		return sdf.format(calendar.getTime());
	}

	public String getWallAttachments() throws JSONException {
		if (mJsonObjectItem.isNull("attachments")) {
			return "";
		}
		return getAttachmentsArray(mJsonObjectItem.getJSONArray("attachments"));
	}
	
	public String getItemLikes() throws JSONException {
		return mJsonObjectItem.getJSONObject("likes").getString("count");
	}
	
	public String getItemName() throws JSONException {
		if(mJsonObjectItem.isNull("first_name")){
			return mJsonObjectItem.getString("name");
		}
		return mJsonObjectItem.getString("first_name")+" "+mJsonObjectItem.getString("last_name"); 
		}

	private String getAttachmentsArray(JSONArray jsonArray)
			throws JSONException {
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < jsonArray.length(); i++) {
			if (jsonArray.getJSONObject(i).getString("type").compareTo("photo") == 0) {
				result.append(jsonArray.getJSONObject(i).getJSONObject("photo")
						.getString("src"));
			}
		}
		if (result.toString().compareTo("") == 0) {
			return "";
		}
		return result.toString();
	}

	public static String[] convertAttachmentsArray(String s) {
		String[] result;
		if (s.compareTo("") != 0) {
			String[] temp = s.split("http://");
			result = new String[temp.length - 1];
			for (int i = 0; i < temp.length; i++) {
				if (temp[i].compareTo("") != 0) {
					temp[i] = "http://" + temp[i];
					result[i - 1] = temp[i];
				}
			}
			return result;
		}
		result = new String[1];
		result[0] = s;
		return result;
	}
}
